<template>
    <div>
        <!-- 条件查询 -->
        <a-row>
            <a-col :span="7">
                <div style="display: flex;">
                    <a-select v-model:value="materialOne">
                        <a-select-option value="1">素材名称</a-select-option>
                        <a-select-option value="2">素材类型</a-select-option>
                        <a-select-option value="3">文件夹名称</a-select-option>
                    </a-select>

                    <a-input v-show="materialOne == '1'" class="search-input" v-model:value="queryData.material_name"
                        placeholder="请输入素材名称" />
                    <a-select v-show="materialOne == '2'" mode="multiple" class="search-select" @change="handleChange"
                        v-model:value="material_types" placeholder="请选择素材类型">
                        <a-select-option v-for="(item, index) in material_types_options" :key="index"
                            :value=item.value>{{ item.label }}</a-select-option>
                    </a-select>

                    <a-cascader v-show="materialOne == '3'" :max-tag-count="1" class="search-cascader"
                        v-model:value="merchant_folder_statck_ids" :options="materialsOptions"
                        @change="change_materials" placeholder="请选择文件夹" />

                </div>
            </a-col>
            <a-col :span="5" style="margin-right: 10px;">
                <a-range-picker class="choose_pivker" format="YYYY-MM-DD" v-model:value="times" :locale="locale"
                    @change="changepicker" />

            </a-col>

            <a-col :span="4">
                <a-cascader class="tag_select" multiple="true" v-model:value="modelTags" :options="chooseTags"
                    @change="change_Tag" placeholder="标签范围" />

            </a-col>

            <a-col :span="3">
                <a-button class="addMa_btn" type="primary" @click="open_update">上传素材</a-button>
            </a-col>


        </a-row>

        <!-- 卡片内容 -->
        <div class="maContent">

            <div class="ma_box" v-if="multimeData.length > 0" v-for="(item, index) in multimeData" :key="index">
                <div class="ma_box_Top" :class="{ 'ma_box_Top_disabled': onechecked && !item.checked }"
                    @mouseover="showMask(index)" @mouseout="hideMask(index)" @click="monicheckbox(index)">
                    <!-- 默认背景色  为黑色 有4种格式   视频 / 图片 / 音频 / 文本 -->

                    <img v-if="item.material_type == 'video' && item.cover_url" class="ma_box_Top_img"
                        :src=item.cover_url>
                    <img v-if="item.material_type == 'image'" class="ma_box_Top_img" :src=item.material_url>

                    <cu-icon v-if="item.material_type == 'audio'" class="ma_box_Top_audio" type="icon-audio" />

                    <span class="ma_box_Top_text" v-if="item.material_type == 'text'">{{ item.material_content }}</span>

                    <!-- 持续时长 -->
                    <div v-if="item.material_type == 'video' || item.material_type == 'audio'"
                        class="ma_box_Top_duration">{{
                            item.material_duration_text }}</div>

                    <div class="ma_box_Top_duration_logo">
                        <cu-icon v-if="item.material_type == 'video'" class="ma_box_Top_mask_icon"
                            type="icon-shiping" />
                        <cu-icon v-if="item.material_type == 'audio'" class="ma_box_Top_mask_icon" type="icon-yinyue" />
                        <cu-icon v-if="item.material_type == 'image'" class="ma_box_Top_mask_icon" type="icon-img" />
                        <cu-icon v-if="item.material_type == 'text'" class="ma_box_Top_mask_icon" type="icon-word" />
                    </div>

                    <!-- 鼠标悬停遮罩层 -->
                    <div class="ma_box_Top_mask" :class="{ 'always-visible': item.checked }">
                        <div class="ma_box_Top_mask_item">
                            <a-checkbox class="Top_mask_checkbox" v-model:checked="item.checked"
                                @change="checkbox_change"></a-checkbox>
                            <eye-outlined @click="previewMaterial(item)" style="color: #fff; font-size: 18px;" />
                            <!-- <cu-icon @click="previewMaterial(item)" style="color: #fff; font-size: 18px;"
                                type="icon-shiping" /> -->
                        </div>

                    </div>

                </div>

                <div class="ma_box_Title">
                    {{ item.material_name }}
                </div>

                <div class="ma_box_Time">
                    {{ item.created_at }}
                </div>

                <div class="ma_box_Tag">
                    <a-tag class="ma_box_Tag_item" v-for="(v1, index1) in item.tag" :key="index1">
                        {{ v1 }}
                    </a-tag>
                </div>
            </div>

            <div v-else class="no-shuju">
                暂无内容
            </div>
        </div>

        <!-- 底部分页 -->
        <div class="bottom-Page">
            <div class="bottom-Page-left">
                <a-pagination size="small" :total="totalNum" v-model:current="queryData.page" @change="onPageChange" />

                <a-checkbox :disabled="isClip" class="all_checkbox" v-model:checked="checkAll"
                    @change="handleSelectAllChange">
                    本页全选
                </a-checkbox>
            </div>

            <div class="bottom-Page-right">
                <a-button @click="closepage">
                    取消
                </a-button>

                <a-button type="primary" @click="onSubmit" class="bottom-page-btn">
                    导入
                </a-button>
            </div>




        </div>

        <!-- 上传素材卡片 -->
        <a-modal v-if="updatevisible" v-model:visible="updatevisible" title="上传素材" @ok="handleOk" @cancel="onClose"
            :zIndex="1021">
            <a-form :model="formState" :colon="false">
                <a-form-item label="选择项目" v-if="is_merchant_library == '1'">
                    <a-cascader class="formState_one" v-model:value="formState.groupname" :options="modelXiang"
                        placeholder="请选择项目" @change="change_groupname" />
                </a-form-item>

                <a-form-item label="文件夹类型">
                    <a-select v-model:value="formState.material_type" placeholder="请选择文件夹类型" @change="change_type">
                        <a-select-option v-for="(item, index) in material_types_options" :key="index"
                            :value=item.value>{{ item.label }}</a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="文件夹名称">

                    <div class="formState_material">
                        <a-select class="formState_name" v-model:value="formState.merchant_folder_statck_id"
                            placeholder="请选择文件夹名称">
                            <a-select-option v-for="(item, index) in material_types_smallName" :key="index"
                                :value=item.value>{{ item.label }}</a-select-option>
                        </a-select>


                        <a-button @click="AddNewmaterial" :disabled="!isAdd">
                            新增文件夹
                        </a-button>
                    </div>

                </a-form-item>

                <a-form-item :label="material_name">
                    <div class="Add_box">
                        <a-tooltip placement="top">
                            <template #title>
                                <span
                                    v-if="formState.material_type == 'video'">支持的视频素材：.mp4,.mov,.3gp,文件≤500M、时长≤900秒、分辨率480p~4k</span>
                                <span
                                    v-if="formState.material_type == 'image'">图片格式：.jpg,.jpeg,.png,最小图片尺寸为200*200，单张图片不可大于20M</span>
                                <span v-if="formState.material_type == 'audio'">音频格式：.mp3,.m4a,.aac</span>
                            </template>
                            <question-circle-outlined v-if="formState.material_type !== 'text'" class="Add_qu" />
                        </a-tooltip>
                        <!-- :directory="true"   文件夹上传-->
                        <a-upload-dragger v-if="formState.material_type !== 'text'" class="model_upload"
                            :action="$utils.fileAction" @drop="handleDrop"
                            :style="{ 'display': fileList.length > 0 ? 'none' : 'block' }"
                            :headers="{ 'org-token': $store.getters.token }" v-model:file-list="fileList"
                            @change="handleLogoUpload" :max-count="10" :before-upload="beforeUpload" :multiple="true"
                            name="file" :data="{ dir: 'work_ai' }" :accept="formState.material_type == 'video'
                                ? '.mp4,.mov,.3gp'
                                : formState.material_type == 'image'
                                    ? '.jpg,.jpeg,.png'
                                    : formState.material_type == 'audio'
                                        ? '.mp3,.m4a,.aac'
                                        : ''" list-type="picture-card">
                            <div v-if="!fileList.length">
                                <cloud-upload-outlined />
                                <div>上传素材</div>
                            </div>
                            <template #itemRender="{ file }">
                                <a-spin :spinning="file.percent === 100 && file.url ? false : true">
                                    <!-- :spinning="fileList.length && fileList[0].url ? false : true" -->
                                    <template #tip>
                                        <span style="color: #fff">上传中...</span>
                                    </template>
                                    <a-row class="file-list" @click="previewClick(file)">
                                        <a-col class="file-content">
                                            <video v-if="formState.material_type == 'video' && file.url" :src="file.url"
                                                style="width: 100%; height: 105px" />
                                            <img v-if="formState.material_type == 'image' && file.url" :src="file.url"
                                                style="width: 100%; height: 105px; object-fit: contain" />
                                            <!-- src/common/image/workShotstackImage/audio.png -->
                                            <img v-if="formState.material_type == 'audio'"
                                                src="@/common/image/workShotstackImage/audio.png "
                                                style="width: 70px; height: 100%; border-radius: 4px" />
                                            <div class="file-mask">
                                                <cu-icon class="icon" type="icon-play"
                                                    style="font-size: 65px"></cu-icon>
                                            </div>
                                        </a-col>
                                        <a-col class="file-name" @click.stop>
                                            <a-col class="text-ellipsis">
                                                {{ file.name }}
                                            </a-col>
                                            <a-col>
                                                <delete-outlined style="cursor: pointer"
                                                    @click.stop="deleteFille(file.uid)" />
                                            </a-col>
                                        </a-col>
                                    </a-row>
                                </a-spin>
                            </template>
                        </a-upload-dragger>

                        <div v-if="formState.material_type == 'text'" class="text-content">
                            <a-textarea v-model:value="formState.headline" show-count :maxlength="5000" :rows="4"
                                placeholder="请输入文案" />
                        </div>
                    </div>

                </a-form-item>
            </a-form>
        </a-modal>


        <!-- 新建文件夹 -->
        <NewFolder :is_merchant_library="is_merchant_library" :material_type="formState.material_type"
            :visible="addVisible" :groupData="currentLibrary" @onCancel="addVisible = false" @onSubmit="closeAdd"
            :checkedSelectType="formState.material_type" />

        <!-- 预览弹框 -->
        <PreviewModal :visible="visiblePreview" :title="fileData.name" :url="fileData.url"
            :type="formState.material_type" @onCancel="visiblePreview = false" />

        <!-- 详情弹框 -->
        <!-- <FileDetailModal 
        :visible="previewVisible" 
        :data="fileData" 
        :index="fileIndex" 
        @addTagChange="addTag"
        @onClose="closePreview" /> -->

        <materialPreview :visible="previewVisible" :materialDetail="materialDetail" @close="closePreview" />

    </div>
</template>

<script setup>
import { ref, watch, defineEmits, defineProps, toRaw } from "vue";
import moment from "moment";
import request from "../../../../../../common/utils/request";
import NewFolder from "../../../../MaterialCenter/modules/NewFolder.vue";
import PreviewModal from "@/components/PreviewModal/index.vue";
import { message } from "ant-design-vue";
import materialPreview from "../../sourceMaterial/modules/materialPreview.vue";
import FileDetailModal from "@/views/shotstack/MaterialCenter/modules/FileDetailModal.vue";



import {
    CloudUploadOutlined,
    DeleteOutlined,
    QuestionCircleOutlined,
    EyeOutlined
} from "@ant-design/icons-vue";
const emit = defineEmits(["onsubmit", "closepage"]);

const queryData = ref({
    material_name: "",     //素材名称
    folder_use_type: 1,   //文件夹使用类型 ( 1- 剪辑素材，2-成片素材)
    page: 1,
    pageSize: 10,
    material_type: "",     //素材类型（多个以英文逗号连接）
    multimedia_tag: "",     // 素材标签（多个以英文逗号连接）
    start_time: "",
    end_time: "",
    is_merchant_library: 1,    //1-项目素材，0-通用素材
    merchant_folder_statck_id: ""
})

const merchant_folder_statck_ids = ref([])

const formState = ref({
    groupname: "",
    material_type: "",    // 素材类型（video、audio 、image）
    merchant_folder_statck_id: "",    //文件夹ID
    material_name: "",     //素材名称
    material_extension: "",  //素材扩展名（例如:mp4,m4a,mp3,jpg,png等）,
    material_size: "",    // 素材大小（byte）
    material_path: "",    // 素材相对路径
    material_url: "",     // 素材URL地址
    cut_config: "",       // material_type=video 可以传递，参数内容：start,end（阈值1-15秒）
    group_id: "",         // 文件夹组id
    down: 0,              // 需要下载到本地（1：是，0：否），不传默认否
    headline: []
});

const previewVisible = ref(false)

const props = defineProps({
    modelType: {
        type: String,
        default: ''
    },
    is_merchant_library: {
        type: String,
        default: ''
    },
    isClip: {
        type: Boolean,
        default: 'false'
    }
})
const times = ref([])
const totalNum = ref(0)
const materialOne = ref("1")
const material_types = ref([])
const material_types_options = ref([])
const modelTags = ref([])
const modelXiang = ref([])
const chooseTags = ref([])



const addVisible = ref(false)

const updatevisible = ref(false)


const checkAll = ref(false)

const multimeData = ref([])
// 获取模块数据
const getmaContent = () => {


    request.get("/work_ai", "/user/shotstack/media/lists", queryData.value)
        .then(async (res) => {
            totalNum.value = res.result.total
            multimeData.value = res.result.data.map(item => ({
                ...item,
                checked: false
            }));
        })
}


// 获取标签数据
const getAllTags = () => {
    request.get("/work_ai", "/user/shotstack/multimedia/group/tag/all")
        .then(async (res) => {
            res.result.forEach(v1 => {
                let newItem = {
                    value: v1.id,
                    label: v1.name,
                };
                if (v1.tags && Array.isArray(v1.tags) && v1.tags.length > 0) {
                    // 构造 children 数组
                    newItem.children = v1.tags.map(v2 => ({
                        value: v2.id,
                        label: v2.name,
                    }));
                }
                chooseTags.value.push(newItem);
            });
        })
}

const materialsOptions = ref([])
const Modelmaterials = ref([])


// 文件夹三级联动
const getmaterials = () => {
    request.get("/work_ai", "/user/user/shotstack/library/folder")
        .then(async (res) => {
            console.log(res, '文件夹三级联动');
            res.result.forEach(v1 => {
                let newItem = {
                    value: v1.id,
                    label: v1.name,
                };
                if (v1.group_and_folder && Array.isArray(v1.group_and_folder) && v1.group_and_folder.length > 0) {
                    // 构造 children 数组
                    newItem.children = v1.group_and_folder.map(v2 => ({
                        value: v2.id,
                        label: v2.group_name,
                        ...(v2.get_folder_statck && Array.isArray(v2.get_folder_statck) && v2.get_folder_statck.length > 0 ? {
                            children: v2.get_folder_statck.map(v3 => ({
                                value: v3.id,
                                label: v3.folder_name,
                            }))
                        } : {}),
                    }));
                }
                materialsOptions.value.push(newItem);

                console.log(materialsOptions.value, '三级联动数据效果2313132132131232113');
            });
        })
}

// 页面初始化
const initData = () => {
    getmaterials()
    getAllTags()
}

initData()

// 翻页
const onPageChange = (page, pageSize) => {
    queryData.value.page = page;
    checkAll.value = false
    getmaContent();
};

//选中标签 
const change_Tag = (e) => {
    let newarr = []
    e.forEach(item => {
        if (item.length == 2) {
            // 单选
            newarr.push(item[1])
        } else if (item.length == 1) {
            chooseTags.value.forEach(v1 => {
                if (v1.value == item[0]) {
                    v1.children.forEach(v2 => {
                        newarr.push(v2.value)
                    })
                }
            })

        }

    })
    queryData.value.multimedia_tag = newarr.join(',');
    queryData.value.page = 1
    getmaContent()
}


// 监听 搜索  一触即发
watch(
    () => queryData.value,
    (val) => {
        if (val) getmaContent()
    },
    { deep: true }
);

// 监听 
watch(
    () => merchant_folder_statck_ids.value,
    (val) => {
        if (val) {
            queryData.value.merchant_folder_statck_id = merchant_folder_statck_ids.value[merchant_folder_statck_ids.value.length - 1]
        }
    },
    { deep: true }
);

const onechecked = ref(false)
const checkbox_change = () => {
    if (props.isClip == true) {
        onechecked.value = !onechecked.value
    }
}

const monicheckbox = (index) => {
    multimeData.value[index].checked = !multimeData.value[index].checked
    if (props.isClip == true) {
        onechecked.value = !onechecked.value
    }
}



// 监听 素材类型
watch(
    () => props.modelType,
    (val) => {
        if (val) {
            switch (val) {
                case 'imgeVideo':
                    material_types_options.value.push(
                        {
                            label: "视频",
                            value: "video"
                        },
                        {
                            label: "图片",
                            value: "image"
                        },
                    )
                    formState.value.material_type = 'video'
                    queryData.value.material_type = 'video,image'
                    // material_types.value.push('video')
                    break;
                case 'audio':
                    material_types_options.value.push(
                        {
                            label: "音频",
                            value: "audio"
                        }
                    )
                    formState.value.material_type = 'audio'
                    queryData.value.material_type = 'audio'
                    // material_types.value.push('audio')
                    break;
                case 'text':
                    material_types_options.value.push(
                        {
                            label: "文本",
                            value: "text"
                        }
                    )
                    formState.value.material_type = 'text'
                    queryData.value.material_type = 'text'
                    // material_types.value.push('text')
                    break;
                case 'image':
                    material_types_options.value.push(
                        {
                            label: "文本",
                            value: "image"
                        }
                    )
                    formState.value.material_type = 'image'
                    queryData.value.material_type = 'image'
                    // material_types.value.push('image')
                    break;
                case 'video':
                    material_types_options.value.push(
                        {
                            label: "视频",
                            value: "video"
                        }
                    )
                    formState.value.material_type = 'video'
                    queryData.value.material_type = 'video'
                    // material_types.value.push('video')
                    break;
                default:
                    // 这里可以处理其他情况，或者什么都不做
                    break;
            }
        }
    },
    {
        immediate: true,
        deep: true
    }
);

const material_name = ref("")

watch(
    () => formState.value.material_type,
    (val) => {
        switch (val) {
            case 'video':
                material_name.value = "视频";
                break;
            case 'image':
                material_name.value = "图片";
                break;
            case 'text':
                material_name.value = "文本";
                break;
            default:
                material_name.value = "音频";
                break;
        }
    },
    {
        immediate: true,
        deep: true
    }
);

// 素材类型 控件
const handleChange = (e) => {
    if (e && e.length > 0) {
        queryData.value.material_type = material_types.value.join(',');
    }

    if (e.length == 0) {
        if (formState.value.material_type == 'video' && material_types_options.value.length > 1) {
            queryData.value.material_type = 'video,image'
        } else {
            queryData.value.material_type = formState.value.material_type

        }

    }
    queryData.value.page = 1
    getmaContent()
}

// 日期选择 控件
const changepicker = (e) => {
    if (e && e.length == 2) {
        queryData.value.start_time = moment(e[0]).format('YYYY-MM-DD') + " 00:00:00"
        queryData.value.end_time = moment(e[1]).format('YYYY-MM-DD') + " 23:00:00"
    } else {
        queryData.value.start_time = ""
        queryData.value.end_time = ""
    }
    queryData.value.page = 1
    getmaContent()
}

const showMask = (index) => {
    const rawItem = toRaw(multimeData.value[index]);
    if (!rawItem.checked) {
        multimeData.value[index].tempChecked = true;
    }
}

const hideMask = (index) => {
    if (!multimeData.value[index].checked) {
        delete multimeData.value[index].tempChecked;
    }
}

// 全选
const handleSelectAllChange = (e) => {
    const isChecked = e.target.checked;
    multimeData.value.forEach(item => {
        item.checked = isChecked;
    });
}



// 上传素材
const open_update = () => {
    updatevisible.value = true
    getLibraryList()
}

const currentLibrary = ref([])
// 新建文件夹 
const AddNewmaterial = () => {
    if (props.is_merchant_library == '1') {
        function findNestedItem(data, targetPath) {
            for (const item of data) {
                if (item.value === targetPath[0]) {
                    if (targetPath.length === 1) {
                        return item;
                    } else if (item.children) {
                        const foundInChildren = findNestedItem(item.children, targetPath.slice(1));
                        if (foundInChildren) {
                            return foundInChildren;
                        }
                    }
                }
            }
            return null;
        }
        const pathToFind = [formState.value.groupname[0], formState.value.groupname[1]];
        currentLibrary.value = findNestedItem(modelXiang.value, pathToFind);
    }

    addVisible.value = true
}




// 左侧大目录
const getLibraryList = () => {
    request
        .get("/work_ai", "/user/shotstack/library/withGroup/list", {
            merchant_library_id: -1,
        })
        .then((res) => {
            res.result.forEach(v1 => {
                let newItem = {
                    value: v1.id + 's',     // a-cascader 区分父子级
                    label: v1.name,
                };
                if (v1.folder_group && Array.isArray(v1.folder_group) && v1.folder_group.length > 0) {
                    // 构造 children 数组
                    newItem.children = v1.folder_group.map(v2 => ({
                        value: v2.id,
                        label: v2.group_name,
                        ...v2,
                    }));
                }

                modelXiang.value.push(newItem);
            });
        });
};
// 获取文件夹
const getfolderList = () => {
    let params = {
        folder_use_type: 1,
        material_type: formState.value.material_type ? formState.value.material_type : '',
        merchant_library_id: formState.value.merchant_library_id,
        group_id: formState.value.group_id
    };
    request
        .post("/work_ai", "/user/shotstack/folder/list", params)
        .then((res) => {
            material_types_smallName.value = []
            res.result.data.forEach(item => {
                material_types_smallName.value.push({
                    label: item.folder_name,
                    value: item.id
                })
            })
        });
}

const material_types_smallName = ref([])
// 选择项目 
const change_groupname = (e) => {

    formState.value.group_id = e[1]
    formState.value.merchant_library_id = parseInt(e[0].slice(0, -1), 10);
    getfolderList()

}

// 选择类型
const change_type = (e) => {
    formState.value.merchant_folder_statck_id = ""
    if (formState.value.group_id) {
        getfolderList()
    }
}

// 添加按钮
const closeAdd = (data) => {
    addVisible.value = false;
    getfolderList()
};


const isAdd = ref(false)
watch(
    () => formState.value.groupname,
    (val) => {
        isAdd.value = false

        if (val && val.length > 0) {
            isAdd.value = true
        } else {
            isAdd.value = false
        }
        if (props.is_merchant_library == '0') {
            isAdd.value = true

        }

    },
    {
        immediate: true,
        deep: true
    }
);


const fileList = ref([])
// 上传图片(应用图标)
const handleLogoUpload = (info) => {
    let resFileList = [...info.fileList];
    if (resFileList.length) {
        resFileList.map((file, index) => {
            if (file.response) {
                if (file.response.code == 1000) {
                    file.url = file.response.data.fileUrl;
                } else {
                    message.warning(file.response.msg);
                    resFileList.splice(index, 1);
                    return;
                }
            }

            if (file.size > 1024 * 1024 * 500) {
                resFileList.splice(index, 1);
            }
        });
    }
    fileList.value = resFileList;
};

const handleDrop = (e) => {
}

const imageWidth = ref(0)
const imageHeight = ref(0)

const beforeUpload = (file) => {
    if (formState.value.material_type == "image") {
        const isLt2M = file.size / 1024 / 1024 < 20;
        let w = 0,
            h = 0;
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
            const image = new Image();
            image.src = reader.result;
            image.onload = () => {
                w = image.width;
                h = image.height;
                imageWidth.value = image.width;
                imageHeight.value = image.height;
                if (w <= 199 || h <= 199) {
                    fileList.value = fileList.value.filter(
                        (item) => item.uid !== file.uid
                    );
                    message.error("图片宽度不能小于200px");
                    return false;
                }
                if (!isLt2M) {
                    message.error("文件不可大于 20M!");
                    return false;
                }
                return true;
            };
        };
    }
    if (formState.value.material_type == "video") {
        const isLt2M = file.size / 1024 / 1024 < 500;
        if (!isLt2M) {
            message.error("文件不可大于 500MB!");
        }
        return isLt2M;
    }
};

const visiblePreview = ref(false)
const fileData = ref([])
const start = ref("")
const end = ref("")
const previewClick = (data) => {

    fileData.value = data;
    visiblePreview.value = true;
};

const deleteFille = (uid) => {
    let index = fileList.value.findIndex((item) => item.uid == uid);
    fileList.value.splice(index, 1);
};

// 上传素材 提交按钮
// 记得做防抖
const handleOk = () => {

    if (formState.value.material_type !== 'text') {
        // 图片 / 视频 / 音频 
        if (!fileList.value.length) {
            message.warn("请上传素材");
            return;
        }

        const promiseAll = fileList.value.map((item) => {
            let params = {
                material_type: formState.value.material_type,
                merchant_folder_statck_id: formState.value.merchant_folder_statck_id,
                material_extension:
                    formState.value.material_type == "video"
                        ? ".mp4,.mov,.3gp"
                        : formState.value.material_type == "image"
                            ? ".jpg,.jpeg,.png"
                            : formState.value.material_type == "audio"
                                ? ".mp3,.m4a,.aac"
                                : undefined,

                material_name: item.name,
                material_size: item.size,
                material_path: "/" + item.response.data.fileName,
                material_url: item.response.data.fileUrl,
                group_id: formState.value.group_id ? formState.value.group_id : 0,
            };

            if (formState.value.material_type == "video" && (start.value || end.value)) {
                params.cut_config = [start.value, end.value];
            }
            //    if(props.is_merchant_library == '0') {
            //     params.
            //    }


            return request.post("/work_ai", "/user/shotstack/media", params);
        });

        Promise.all(promiseAll)
            .then(() => {
                message.success("上传成功");
                updatevisible.value = false
                fileList.value = []
                queryData.value.page = 1
                getmaContent()
            })
    } else {
        // 文本 保存
        let arr = []
        arr.push(formState.value.headline)
        let params = {
            merchant_folder_statck_id: formState.value.merchant_folder_statck_id,
            material_type: 'text',
            headline: arr,
        };

        request
            .post("/work_ai", "/user/shotstack/text", params)
            .then((res) => {
                message.success("添加成功");
                updatevisible.value = false
                formState.value.headline = ""
                formState.value.groupname = ""
                formState.value.merchant_folder_statck_id = ""
                material_types_smallName.value = []
                queryData.value.page = 1
                getmaContent()
                // emit("onSubmit");
                // state.loading = false;
            })
            .catch(() => {
                // state.loading = false;
            });
    }




}


const onClose = () => {
    updatevisible.value = false
    fileList.value = []
}

const onSubmit = () => {
    let newarr = []
    multimeData.value.forEach(item => {
        if (item.checked == true) {
            newarr.push(item)
        }
    })

    emit("onsubmit", newarr)
}

const closepage = () => {
    emit("closepage")

}

const dynamicValidateForm = ref({
    users: [
        {
            name: "",
        },
    ],
})
const materialDetail = ref({})
const previewMaterial = (item) => {
    previewVisible.value = true;
    materialDetail.value = item;
};
const closePreview = () => {
    previewVisible.value = false;
    materialDetail.value = {};
};
// 监听 素材类型
watch(
    () => props.is_merchant_library,
    (val) => {
        if (val) {
            queryData.value.is_merchant_library = val
            //  通用素材 时 调用一下 下拉接口

            if (val == '0') {
                console.log('通用素材 时 调用一下 下拉接口');
                getfolderList()
            }
        }
    },
    {
        immediate: true,
        deep: true
    }
);
</script>

<style lang="less" scoped>
.search-input {
    width: 230px;
}

.search-select {
    width: 230px;
}

.search-cascader {
    width: 230px;
}

.choose_pivker {
    margin-left: 10px;
}

.tag_select {
    margin-right: 20px;

}

.rule_select {
    margin-left: 10px;
}

.addMa_btn {
    border-radius: 4px;
}


// 卡片内容
.maContent {
    margin: 20px 0 40px 0;
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    min-height: 442px !important;

    .ma_box {
        margin: 0 10px 10px 0;
        transition: background-color 0.3s ease;
        padding: 5px;
        border-radius: 8px;
        height: 200px;

        &:hover {
            background-color: #f2f2f2;
        }

        // 卡片样式   有4种格式   视频 / 图片 / 音频 / 文本
        .ma_box_Top {
            width: 204px;
            height: 120px;
            background-color: #000;
            border-radius: 8px;
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;

            // 视频
            .ma_box_Top_video {
                width: 100%;
                height: 100%;
            }

            .ma_box_Top_img {
                width: 100%;
                height: 100%;
                border-radius: 8px;
                object-fit: cover;

            }

            .ma_box_Top_audio {
                font-size: 40px
            }

            .ma_box_Top_text {
                color: #fff;
                font-size: 16px;
                width: 160px;
                display: -webkit-box;
                -webkit-line-clamp: 4;
                -webkit-box-orient: vertical;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            //持续时长
            .ma_box_Top_duration {
                color: #fff;
                position: absolute;
                bottom: 5px;
                right: 5px;
            }

            .ma_box_Top_duration_logo {
                color: #fff;
                position: absolute;
                bottom: 5px;
                left: 10px;

                .ma_box_Top_mask_icon {
                    color: #fff;
                    font-size: 20px;
                }
            }

            .ma_box_Top_mask {
                display: none;
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 30px;
                background-color: rgba(0, 0, 0, 0.5);
                border-radius: 8px 8px 0 0;
                transition: opacity 0.3s ease;
                padding: 5px 10px;

                .ma_box_Top_mask_item {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;


                }
            }

        }

        .ma_box_Top_mask.always-visible {
            display: block !important;
        }

        .ma_box_Top:hover .ma_box_Top_mask {
            display: block;
        }

        .ma_box_Title {
            width: 180px;
            text-align: left;
            font-size: 16px;
            font-weight: 700 !important;
            margin-top: 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .ma_box_Time {
            width: 180px;
            text-align: left;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .ma_box_Tag {
            margin-top: 5px;
            width: 204px;
            height: 24px;
            overflow: hidden;

            .ma_box_Tag_item {
                max-width: 80px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }


    }
}

// 底部分页
.bottom-Page {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;

    .bottom-Page-left {
        display: flex;

        .all_checkbox {
            margin-left: 20px;
        }
    }

    .bottom-Page-right {
        display: flex;

        .bottom-page-btn {
            margin-left: 20px;
            border-radius: 4px;
        }
    }

}

.formState_one {
    margin-left: 12px;
    width: 390px;
}


.formState_material {
    display: flex;

    .formState_name {
        margin-right: 10px;
    }
}


:deep(.ant-upload-list-picture-card-container) {
    margin: 0 8px 60px 0;
}

:deep(.ss-upload-list-picture-card-container) {
    margin-bottom: 35px;
}

:deep(.model_upload) {
    margin-left: 42px !important;
    height: 120px !important;
    width: 220px !important;
}

:deep(.ss-upload-list-picture-card) {
    margin-left: 42px !important;
}

:deep(.ss-upload-list) {
    margin-left: 42px !important;
}


.file-list {
    width: 102px;
    height: 120px;
    text-align: center;
    padding-bottom: 50px;
    margin-bottom: 10px;

    .file-content {
        width: 102px;
        height: 105px;
        background: #000;
        margin-bottom: 5px;
        cursor: pointer;
        position: relative;

        .file-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 102px;
            height: 105px;
            text-align: center;
            line-height: 138px;
            background: #000;
            opacity: 0;
            color: #fff;
        }

        &:hover {
            .file-mask {
                opacity: 0.3;
            }
        }
    }

    .file-name {
        width: 100%;
        display: flex;

        .text-ellipsis {
            width: 110px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
}

.text-content {
    height: 320px;
    overflow: auto;
}

.footer {
    width: 100%;
    text-align: right;
    margin-top: 40px;
}

.model_upload {
    margin-left: 43px;
}

.Add_box {
    display: flex;
    position: relative;
    padding-top: 8px;

    .Add_qu {
        position: absolute;
        left: -6px;
        font-size: 16px;
    }
}

.no-shuju {
    font-size: 16px;
    color: #999;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.ma_box_Top_disabled {
    opacity: 0.5 !important;
    pointer-events: none !important;
}


.text-content {
    width: 100%;
    // height: 320px;
    overflow: auto;
    margin-left: 43px;
}
</style>